package model;

import java.util.ArrayList;

import controls.CenterTimer;
import controls.Refreshable;

public class taskQueueUtility implements Refreshable {
	private static final long serialVersionUID = -8326425421791531033L;

	private ArrayList<TaskElement> taskQueue;
	private Tasks normalTasks;

	public taskQueueUtility(Tasks tasks) {
		taskQueue = new ArrayList<TaskElement>();
		normalTasks = tasks;

		CenterTimer.getInstance().addToControlRefreshList(this);
	}

	public void addToTaskQueue(int source, int dest) {
		TaskElement e = new TaskElement(source, dest);
		taskQueue.add(e);

		CenterTimer.getInstance().addToRight(e);
	}

	public void addToTaskQueue(TaskElement e) {
		taskQueue.add(e);

		CenterTimer.getInstance().addToRight(e);
	}

	public ArrayList<TaskElement> getTasksOfLevel(int level) {
		ArrayList<TaskElement> result = new ArrayList<TaskElement>();
		TaskElement e;
		for (int i = 0; i < taskQueue.size(); i++) {
			e = taskQueue.get(i);
			if (e.getSource() == level)
				result.add(e);
		}
		return result;
	}

	@Override
	public void refresh() {
		TaskElement temp;
		int size = taskQueue.size();

		TaskElement[] toAdd = new TaskElement[size];
		int index = 0;

		for (int i = 0; i < size; i++) {
			temp = taskQueue.get(i);
			if (temp.getTimeUnit() <= 0) {
				toAdd[index] = temp;
				index++;
			}
		}

		for (int i = 0; i < index; i++) {
			normalTasks.addTask(toAdd[i]);
			taskQueue.remove(toAdd[i]);
		}

	}

}
